package com.yyfax.ph.personal.authority.phonechange;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.form.ClearEditText;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.BuildConfig;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.Constants.TimerTask;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.verifycode.VerifyCodeModel;
import com.yyfax.ph.personal.authority.verifycode.VerifyCodePresenter;

public class ChangeNewPhoneActivity extends BaseYYFaxActivity implements TextWatcher, ChangeNewPhonePresenter.View, VerifyCodePresenter.View {

	private static final String TAG = ChangeNewPhoneActivity.class.getSimpleName();

	private final static int LOAD_ID_MODIFY_NEW_PHONE = 1;
	private final static int LOAD_ID_VERIFY_CODE = 2;

	public final static String OLD_PHONE = "oldPhone";
	public final static String VERIFY_ID = "verifyId";

	@BindView(R.id.new_phone_number_tv)
	ClearEditText mNewPhoneEdit;
	@BindView(R.id.verify_code_input_edit_tv)
	ClearEditText mVerifyEdit;
	@BindView(R.id.get_verify_tv)
	TextView mGetVerifyTv;
	@BindView(R.id.second_confirm_password_btn)
	Button mChangeBtn;

	private String mOldPhone;
	private String mVerifyId;
	private ChangeNewPhonePresenter mChangeNewPhonePresenter;
	private VerifyCodePresenter mVerifyCodePresenter;

	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.change_new_phone_activity_layout;
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
		if (null == getIntent())
			return;
		if (getIntent().hasExtra(ChangeNewPhoneActivity.OLD_PHONE))
			mOldPhone = getIntent().getStringExtra(ChangeNewPhoneActivity.OLD_PHONE);
		if (getIntent().hasExtra(ChangeNewPhoneActivity.VERIFY_ID))
			mVerifyId = getIntent().getStringExtra(ChangeNewPhoneActivity.VERIFY_ID);
	}

	@Override
	protected void onStop() {
		super.onStop();
		getSupportLoaderManager().destroyLoader(LOAD_ID_MODIFY_NEW_PHONE);
		getSupportLoaderManager().destroyLoader(LOAD_ID_VERIFY_CODE);
	}

	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(LOAD_ID_MODIFY_NEW_PHONE, null, this);
		getSupportLoaderManager().initLoader(LOAD_ID_VERIFY_CODE, null, this);
	}

	private TimerTask timerTask = new TimerTask() {

		@Override
		public void onTime(int time) {
			mGetVerifyTv.setTextColor(getResources().getColor(R.color.color_999999));
			mGetVerifyTv.setText(getString(R.string.count_decrease, Constants.TIME - time));
			mGetVerifyTv.setEnabled(false);
		}

		@Override
		public void onEnd() {
			mGetVerifyTv.setText(getString(R.string.re_get_obtain));
			mGetVerifyTv.setEnabled(true);
			mGetVerifyTv.setTextColor(getResources().getColor(R.color.color_2b92ec));
		}

		public String getKey() {
			return TAG;
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		Constants.timerTask = timerTask;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Constants.timerTask = null;
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOAD_ID_MODIFY_NEW_PHONE:
				return new PresenterLoader<>(this, new ChangeNewPhonePresenter.Generator());
			case LOAD_ID_VERIFY_CODE:
				return new PresenterLoader<>(this, new VerifyCodePresenter.Generator());
			default:
				break;
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOAD_ID_MODIFY_NEW_PHONE:
				mChangeNewPhonePresenter = (ChangeNewPhonePresenter) data;
				mChangeNewPhonePresenter.attach(this);
				break;
			case LOAD_ID_VERIFY_CODE:
				mVerifyCodePresenter = (VerifyCodePresenter) data;
				mVerifyCodePresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitleLeftVisible(false);
		setTitleVisible(true);
		setTitle(R.string.change_phone_strs);

		mTitleCenter.setTextSize(TypedValue.COMPLEX_UNIT_PX, DensityUtil.dip2px(this, 18));
		mTitleCenter.setTextColor(getResources().getColor(R.color.color_262932));
		mNewPhoneEdit.addTextChangedListener(this);
		mVerifyEdit.addTextChangedListener(this);
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		inputWatch(mNewPhoneEdit, mVerifyEdit);
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		inputWatch(mNewPhoneEdit, mVerifyEdit);
	}

	private void inputWatch(EditText mOldPhoneTv, EditText mVerifyTv) {
		String mOldPhone = mOldPhoneTv.getText().toString();
		String verifyCode = mVerifyTv.getText().toString().trim();
		if (!TextUtils.isEmpty(mOldPhone)) {
			if (!RegexUtil.isMobileNumber(mOldPhone)) {
				mOldPhoneTv.setFocusable(true);
				enableView(mGetVerifyTv, false);
			} else {
				enableView(mGetVerifyTv, true);
			}
		} else {
			enableView(mGetVerifyTv, false);
		}
	}

	private void enableView(View view, boolean enable) {
		view.setEnabled(enable);
	}

	@Override
	public VerifyCodeModel.VerifyCodeParams getVerifyParams(String verifyCodeType) {
		VerifyCodeModel.VerifyCodeParams verifyCodeParams = new VerifyCodeModel.VerifyCodeParams();
		verifyCodeParams.phone = mNewPhoneEdit.getText().toString();
		verifyCodeParams.type = verifyCodeType;
		verifyCodeParams.code = mVerifyEdit.getText().toString();
		return verifyCodeParams;
	}

	@Override
	public void obtainVerifyCodeSuccess(String verifyCode) {
		//debug模式下自动填充 生产模式下不会进行
		if (BuildConfig.DEBUG) {
			mVerifyEdit.setText(verifyCode);
		}

		dismissLoading();
		Constants.startTimer(TAG);
		showToast(R.string.verification_code_sent);
		if (Constants.timerTask == null) {
			Constants.timerTask = timerTask;
		}
	}

	@Override
	public void obtainVerifyCodeFailure(String tips) {
		dismissLoading();
		showToast(tips);
		CLog.i(TAG, "获取验证码失败" + tips);
	}

	@Override
	public void checkVerifyCodeSuccess(String code) {
	}

	@Override
	public void checkVerifyCodeFailure(String tips) {
	}

	@Override
	public ChangeNewPhoneModel.ChangePhoneNumParams getChangePhoneNumParams() {
		ChangeNewPhoneModel.ChangePhoneNumParams changePhoneNumParams = new ChangeNewPhoneModel.ChangePhoneNumParams();
		changePhoneNumParams.loginName = mOldPhone;
		changePhoneNumParams.phone = getNewPhone();
		changePhoneNumParams.verifyCode = mVerifyEdit.getText().toString();
		changePhoneNumParams.verifyId = mVerifyId;
		return changePhoneNumParams;
	}

	private String getNewPhone() {
		return mNewPhoneEdit.getText().toString().trim();
	}

	@Override
	public void changePhoneSuccess() {
		dismissLoading();

		showTipsDialog(getString(R.string.change_phone_success_dialog_content), new DialogBase.BottomOneClickListener() {
			@Override
			public void bottomOneClick(DialogBase dialog) {
				YJPH.getInstance().onLogoutSuccess();
				MainActivity.start(ChangeNewPhoneActivity.this, true);
				finish();
			}
		});
	}

	@Override
	public void changePhoneFailure(String tips) {
		dismissLoading();
		showToast(tips);
		if (getString(R.string.verify_code_error).equals(tips)) {
			mVerifyEdit.getText().clear();
		}
	}

	@OnClick({R.id.get_verify_tv, R.id.second_confirm_password_btn})
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.get_verify_tv:
				if (TextUtils.isEmpty(getNewPhone())) {
					showToast(R.string.phone_empty);
				} else {
					mVerifyCodePresenter.obtainVerifyCode(VerifyCodeModel.VERIFY_CODE_TYPE_MODIFY_PHONE_NUM);
				}
				break;
			case R.id.second_confirm_password_btn:
				if (!checkInput()) {
					return;
				}
				mChangeNewPhonePresenter.changePhoneNum();
				break;
		}
	}

	private boolean checkInput() {
		String mNewPhone = mNewPhoneEdit.getText().toString();
		if (TextUtils.isEmpty(mNewPhone)) {
			showToast(getResources().getString(R.string.please_input_toast, getString(R.string.phone_number)));
			return false;
		}
		if (!RegexUtil.isMobileNumber(mNewPhone)) {
			showToast(getResources().getString(R.string.please_input_correct, getString(R.string.phone_number)));
			return false;
		}
		String verifyCode = mVerifyEdit.getText().toString().trim();
		if (TextUtils.isEmpty(verifyCode)) {
			showToast(getResources().getString(R.string.please_input_toast, getString(R.string.verify_code)));
			return false;
		}
		return true;
	}
}
